package com.efrei.uchat.model.user;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import com.efrei.uchat.exception.UChatException;
import com.efrei.uchat.utils.Const;

/**
 * chatter collection. All chatter have different pseudo
 * @author pierrick
 */
public class Chatters {
	private Map<String, Chatter> chatters;

	public Chatters() {
		chatters = new HashMap<String, Chatter>();
	}

	public void addChatter(Chatter chatter) throws UChatException {
		String pseudo = chatter.getPseudo();
		if (isRegistered(chatter)) {
			throw new UChatException(Const.EXCEPTION_PSEUDO_ALREADY_EXISTS);
		}
		// Add chatter
		chatters.put(pseudo, chatter);
	}

	public boolean isRegistered(Chatter chatter) {
		return isRegistered(chatter.getPseudo());
	}

	public boolean isRegistered(String pseudo) {
		return chatters.containsKey(pseudo);
	}

	public Chatter getChatter(String pseudo) throws UChatException {
		if (isRegistered(pseudo))
			return chatters.get(pseudo);
		else
			throw new UChatException(Const.EXCEPTION_CHATTER_DOESNT_EXIST);
	}
	
	/**
	 * remove chatter in chatters registered
	 * @param chatter
	 * @return if chatter was removed
	 */
	public boolean remove(Chatter chatter) {
		return (chatters.remove(chatter.getPseudo())!=null);
	}
	
	/**
	 * rename chatter with newPseudo
	 * @param oldPseudo
	 * @param pseudo
	 * @return if renamed was succeeded
	 */
	public boolean rename(Chatter chatter, String newPseudo) {
		if(chatter == null) {
			return false;
		}
		String oldPseudo = chatter.getPseudo();
		if(oldPseudo.equals(newPseudo)) {
			// same pseudo
			return true;
		}
		if(isRegistered(newPseudo)) {
			// pseudo already taken
			return false;
		}
		chatters.remove(oldPseudo);
		// and rename
		chatter.setPseudo(newPseudo);
		chatters.put(newPseudo, chatter);
		return true;
	}
	
	public Iterator<Chatter> getEnumerable() {
		return chatters.values().iterator();
	}
}
